﻿using System;
using System.Web;


namespace MiniProfilerWebFormsEnabler
{

    public class MiniProfilerHttpModule : IHttpModule
    {
        /// <summary>
        /// By default, the miniprofiler will be started for all requests, but only shown to the user if they
        /// enabled it for their session by going to ~/MiniProfiler/true.  It will queue up to 15 traces
        /// per user, so when you can go back and see what happened when a page loaded slowly.  Set this to 
        /// false in Application_Start
        /// </summary>
        public static bool AlwaysProfile = true;

        /// <summary>
        /// By default, the miniprofiler will be started for all local requests.  If you don't want this
        /// then set this to false in Application_Start
        /// </summary>
        public static bool AlwaysProfileLocalRequests = true;

        #region " Methods "

        /// <summary>
        /// Called by asp.net
        /// </summary>
        /// <param name="context"></param>
        /// <remarks></remarks>
        public void Init(HttpApplication context)
        {

            // wire up the 2 events we care about
            context.EndRequest += OnEndRequest;
            context.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
        }
        public void Dispose()
        {
            // nothing to do here
        }

        #endregion

        #region " Event Handlers "

        public void OnEndRequest(object sender, EventArgs e)
        {
            // stop the miniprofiler.  Doesn't matter if it had been started or not.
            StackExchange.Profiling.MiniProfiler.Stop();
        }


        public void OnPreRequestHandlerExecute(object sender, EventArgs e)
        {
            HttpApplication httpApp = sender as HttpApplication;

            if (httpApp != null)
            {
                System.Web.UI.Page page = httpApp.Context.Handler as System.Web.UI.Page;

                if (page != null)
                {
                    bool enabled;
                    if (httpApp.Context.Session == null)
                    {
                        enabled = false;
                    }
                    else
                    {
                        enabled = (bool)(httpApp.Context.Session[MiniProfilerHttpHandler.MINI_PROFILER_ENABLED_SESSION_KEY] ?? false);
                    }
                    if (MiniProfilerHttpModule.AlwaysProfile || enabled || (httpApp.Request.IsLocal && AlwaysProfileLocalRequests))
                    {
                        if (StackExchange.Profiling.MiniProfiler.Current == null)
                        {
                            StackExchange.Profiling.MiniProfiler.Start(StackExchange.Profiling.ProfileLevel.Verbose);
                        }
                        if (enabled)
                        {
                            page.PreRender += OnPreRender;
                        }
                    }
                }

            }

        }

        public void OnPreRender(object sender, EventArgs e)
        {
            if (HttpContext.Current.Session != null)
            {
                if ((bool)(HttpContext.Current.Session[MiniProfilerHttpHandler.MINI_PROFILER_ENABLED_SESSION_KEY] ?? false))
                {
                    System.Web.UI.Page page = sender as System.Web.UI.Page;

                    page.ClientScript.RegisterStartupScript(page.GetType(), "MiniProfilerStartupScript", StackExchange.Profiling.MiniProfiler.RenderIncludes(StackExchange.Profiling.RenderPosition.Right).ToHtmlString());
                }
            }
            
        }

        #endregion
    }



}
